import React, { useState, useMemo, useRef } from 'react';
import { Select, Spin, Empty, message } from 'antd';
import debounce from 'lodash/debounce';
import { getUserList } from '../../services';

async function fetchUserList(params) {
  return getUserList(params).then((response) => {
    const { code, data, message: errorMessage } = response;
    if (code === 0) {
      return data || [];
    }
    message.error(errorMessage);
    return [];
  });
}

function UserSelect({
  fetchOptions = fetchUserList,
  onSelect,
  debounceTimeout = 800,
  appCode,
  ...props
}) {
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState([]);
  const [value, setValue] = useState(null);
  const fetchRef = useRef(0);
  const debounceFetcher = useMemo(() => {
    const loadOptions = (employeeName = '') => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);
      fetchOptions({ employeeName }).then((newOptions) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }
        setOptions(newOptions);
        setFetching(false);
      });
    };

    return debounce(loadOptions, debounceTimeout);
  }, [debounceTimeout, fetchOptions]);

  return (
    <Select
      labelInValue
      value={value}
      filterOption={false}
      onSearch={debounceFetcher}
      onChange={(newValue) => {
        onSelect({ ...newValue, value: Number(newValue.value) });
        setValue(null);
      }}
      getPopupContainer={triggerNode => triggerNode.parentNode}
      optionLabelProp="label"
      notFoundContent={fetching ? <Spin size="small" /> : fetchRef.current > 0 && <Empty />}
      showSearch
      {...props}
    >
      {options.map(option => (
        <Select.Option
          key={option.id}
          value={option.id}
          label={option.employeeName}
        >
          <div>
            <div>{option.employeeName}</div>
            <span>
              用户名：
              {option.userAccount}
            </span>
            <span>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
            <span>
              工号：
              {option.employeeCode}
            </span>
          </div>
        </Select.Option>
      ))}
    </Select>
  );
}

export default UserSelect;
